package com.zerowidth.moc.web.controller.serviceimpl;

import com.zerowidth.moc.web.auth.TokenHelper;
import com.zerowidth.moc.web.controller.service.AlbumRecordService;
import com.zerowidth.moc.web.resp.ResCode;
import com.zerowidth.moc.web.resp.ResultBean;
import com.zerowidth.moc.web.resp.helper.ResponseCreator;
import com.zerowidth.moc.web.utils.StringUtils;
import com.zerowidth.db.bean.AlbumRecordBean;
import com.zerowidth.db.bean.vm.DaySimpleVM;
import com.zerowidth.db.op.AlbumRecordDB;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

@Service
public class AlbumRecordServiceImpl implements AlbumRecordService {

    @Override
    public ResponseEntity<ResultBean<AlbumRecordBean>> createAlbumRecord(AlbumRecordBean albumRecordBean) {
        AlbumRecordDB.insert(albumRecordBean);

        if (albumRecordBean.id > 0) {
            return ResponseCreator.creatOk(albumRecordBean, ResCode.CODE_OK, "记录保存成功");
        } else {
            return ResponseCreator.creatOk(albumRecordBean, ResCode.ER_20000, "记录保存失败");
        }
    }

    @Override
    public ResponseEntity<ResultBean<Collection<DaySimpleVM>>> getAlbumPageList(
            String userId, String babyId, String day, int count) {
        Collection<DaySimpleVM> recordList = AlbumRecordDB.getAlbumPageList(userId, babyId, day, count);

        return ResponseCreator.creatOk(recordList, ResCode.CODE_OK, "获取相册数据成功");
    }

    @Override
    public ResponseEntity<ResultBean<List<AlbumRecordBean>>> getDayRecordList(
            String babyId, String day, String record_id, int count) {

        List<AlbumRecordBean> recordList = AlbumRecordDB.getDayAlbumPageList(babyId, day, record_id, count);

        return ResponseCreator.creatOk(recordList, ResCode.CODE_OK, "获取单天相册数据成功");
    }

    @Override
    public ResponseEntity<ResultBean<Void>> deleteAlbumRecord(String recordId) {
        String userId = TokenHelper.getUserIdByToken();

        AlbumRecordBean albumRecordBean = AlbumRecordDB.findAlbumRecord(recordId);

        if (albumRecordBean == null) {
            return ResponseCreator.creatOk(null, ResCode.ER_20010, "相册记录不存在");
        } else if (!StringUtils.equals(userId, albumRecordBean.user_id)) {
            return ResponseCreator.creatOk(null, ResCode.ER_20010, "不能删除其它亲友上传的记录");
        } else if (albumRecordBean.delete_flag) {
            return ResponseCreator.creatOk(null, ResCode.CODE_OK, "请勿重复删除");
        } else if (AlbumRecordDB.deleteAlbumRecord(recordId)) {
            return ResponseCreator.creatOk(null, ResCode.CODE_OK, "删除成功");
        } else {
            return ResponseCreator.creatOk(null, ResCode.CODE_OK, "删除失败");
        }
    }

}
